package com.dotstone.chipism.ui.timing;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.NumberPicker;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.dotstone.chipism.R;
import com.dotstone.chipism.activity.BaseActivity;
import com.dotstone.chipism.bean.Device;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.ui.dialog.SelectRemindWayPopup;
import com.dotstone.chipism.ui.timing.bean.TimingData;
import com.dotstone.chipism.ui.timing.util.AddSocketTimingManager;
import com.dotstone.chipism.ui.timing.util.ShareParam;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.util.TimeUtil;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class AddSocketTiming1Activity extends BaseActivity {

    public static final int ADD_SUCCESS_REQUEST_CODE = 0x01;
    public static final int ADD_SUCCESS_RESULT_CODE = 0x02;

    public static TextView tvTitle;
    private TextView mStatusBar;
    private Button btnAdd;
    private View btnBack;
    private NumberPicker npHour , npMIn;//时间跟分钟的选择器
    private RadioGroup rg_switch;
    private Device device;
    private SVProgressHUD mSVProgressHUD;
    List<Boolean>  cbWeeks = new ArrayList<>();;
    private ToggleButton onoff_model;//重复模式
    private boolean isUpdate ; //是否是编辑状态
    private TextView time_tv;
    private TextView save_time_tv;
    private TextView switch_tv;
    private boolean flag=true;
    private int hour1;
    private int minute1;
    private int hour;
    private int minute;
    private String hour111;
    private String minute111;
    private RelativeLayout repeat_rl;
    public static TextView workday_tv;
    private String name;
    private Boolean repeat_mode;
    private boolean sun_selected;
    private boolean sat_selected;
    private boolean fri_selected;
    private boolean thu_selected;
    private boolean wed_selected;
    private boolean tue_selected;
    private boolean mon_selected;
    int addflag;
    private int taskid;
    private String deviceid;

    @Override
    public void widgetClick(View v) {
        switch (v.getId()){
            case R.id.switch_tv:
                 if(flag){
                     flag=false;
                     switch_tv.setText("关闭");
                 }else{
                     flag=true;
                     switch_tv.setText("开启");
                 }
                break;
            case R.id.repeat_rl:
                selectRingWay();
                break;
            case R.id.back_layout:
                finish();
                break;
            //保存
            case R.id.nextstep:
                mSVProgressHUD.showWithStatus("正在保存中...");
                String taskName = "";
                JSONObject obj = new JSONObject();
                try {

                    if (flag){
                        taskName = "开";
                        JSONObject jo = new JSONObject();
                        jo.put("cmd", 101);
                        if (device.getDataOpenCmd() != null && device.getDataOpenCmd().length != 0) {
                            JSONArray ja = new JSONArray();
                            for (int i = 0; i < device.getDataOpenCmd().length; i++) { // 依次将数组元素添加进JSONArray对象中
                                ja.put(device.getDataOpenCmd()[i]);
                            }
                            jo.put("data", ja);
                        }

                        obj.put("body", jo.toString());
                    } else {
                        taskName = "关";
                        JSONObject jo = new JSONObject();
                        jo.put("cmd", 101);
                        if (device.getDataCloseCmd() != null && device.getDataCloseCmd().length != 0) {
                            JSONArray ja = new JSONArray();
                            for (int i = 0; i < device.getDataCloseCmd().length; i++) { // 依次将数组元素添加进JSONArray对象中
                                ja.put(device.getDataCloseCmd()[i]);
                            }
                            jo.put("data", ja);
                        }
                        obj.put("body", jo.toString());
                    }
                    obj.put("hid", DeviceManager.getInstance().hid);
                    if(!workday_tv.getText().toString().equals("执行一次")){
                        repeat_mode=true;
                    }else{
                        repeat_mode=false;
                    }
                    if (repeat_mode){
                        obj.put("cycle", true);//是否重复
                    }else {
                        obj.put("cycle", false);//是否重复
                    }
                    sun_selected=ShareParam.getBooleanParam(this,"sun_selected");
                    sat_selected=ShareParam.getBooleanParam(this,"sat_selected");
                    fri_selected=ShareParam.getBooleanParam(this,"fri_selected");
                    thu_selected=ShareParam.getBooleanParam(this,"thu_selected");
                    wed_selected=ShareParam.getBooleanParam(this,"wed_selected");
                    tue_selected=ShareParam.getBooleanParam(this,"tue_selected");
                    mon_selected=ShareParam.getBooleanParam(this,"mon_selected");
                    if(cbWeeks.size()>0){
                        cbWeeks.clear();
                    }
                    cbWeeks.add(sun_selected);
                    cbWeeks.add(sat_selected);
                    cbWeeks.add(fri_selected);
                    cbWeeks.add(thu_selected);
                    cbWeeks.add(wed_selected);
                    cbWeeks.add(tue_selected);
                    cbWeeks.add(mon_selected);
                    //判断是否有选择
                    boolean isSelected = false;
                    StringBuffer sb = new StringBuffer("0");//默认每天
                    if(workday_tv.getText().toString().equals("执行一次")){
                        sb = new StringBuffer("01111111");
                    }else if(workday_tv.getText().toString().equals("每天")){
                        sb = new StringBuffer("01111111");
                    }else if(workday_tv.getText().toString().equals("工作日")){
                        sb = new StringBuffer("00011111");
                    }else if(workday_tv.getText().toString().equals("周末")){
                        sb = new StringBuffer("01100000");
                    }else{
                        for (int i = 0 ; i < cbWeeks.size() ; i ++) {
                            sb.append(cbWeeks.get(i).toString().equals("true") ? "1": "0");
                            if (cbWeeks.get(i).toString().equals("true")){
                                isSelected = true;
                            }
                        }
                    }
                    //如果都没选中
                    if (!isSelected && !repeat_mode) {
                        // 获取当前时间
                        Calendar calendar = Calendar.getInstance();
                        //小时
                        int hour = calendar.get(Calendar.HOUR_OF_DAY);
                        //分钟
                        int minute = calendar.get(Calendar.MINUTE);

                        boolean isInit = true;

                        //判断小时
                        if (npHour.getValue() < hour) {
                            isInit = false;
                            //小于当前时间，要进一天
                            int currentWeek = 0;
                            int weekDay = new Date().getDay();
                            if (weekDay == 0) {
                                weekDay = 7;
                            }
                            currentWeek = weekDay + 1;
                            if (currentWeek == 8) {
                                currentWeek = 1;
                            }
                            sb.replace(7 -currentWeek + 1 , 7 -currentWeek + 1+ 1  , "1");

                        } else if (npHour.getValue() == hour) {
                            //判断分钟
                            if (npMIn.getValue() <= minute) {
                                isInit = false;
                                //小于当前时间，要进一天
                                int currentWeek = 0;
                                int weekDay = new Date().getDay();
                                if (weekDay == 0) {
                                    weekDay = 7;
                                }
                                currentWeek = weekDay + 1;
                                if (currentWeek == 8) {
                                    currentWeek = 1;
                                }
                                sb.replace(7 - currentWeek+ 1  , 7 -currentWeek + 1+ 1  , "1");
                            }
                        }
                        if (isInit) {
                            //小于当前时间，要进一天
                            int currentWeek = 0;
                            int weekDay = new Date().getDay();
                            if (weekDay == 0) {
                                weekDay = 7;
                            }
                            currentWeek = weekDay;
                            if (currentWeek == 8) {
                                currentWeek = 1;
                            }

                            sb.replace(7 - currentWeek + 1 , 7 -currentWeek + 1 + 1 , "1");
                        }
                    }

                    if (!isSelected && repeat_mode) {
                       // sb = new StringBuffer("01111111");
                    }
                    Log.i("push_week" , "push_week:" + sb.toString());
                    obj.put("push_week", bitToByte(sb.toString()));
                    String min = npMIn.getValue() < 10 ? "" + npMIn.getValue() :""+ npMIn.getValue();
                    obj.put("pushTime", npHour.getValue() + ":" + min);
                    int sendNumber = 0;
                    for (int i = 0 ; i < sb.toString().length() ; i ++) {
                        if (sb.charAt(i) == '1'){
                            sendNumber ++;
                        }
                    }
                    obj.put("sendNumber", sendNumber);//发送次数
                //    obj.put("deviceId", device.getMainDeviceId());
                    obj.put("deviceId", deviceid);
                    obj.put("key", "10000");
                    obj.put("requestTime", "" + System.currentTimeMillis());
                    obj.put("taskName", taskName);
                    obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
                } catch (JSONException e1) {
                    e1.printStackTrace();
                }
//              AddTimingBean a = new AddTimingBean(device.getOpenCmd());
                Log.i("onResponse" , "content:" + obj.toString());


                //save定时数据
                if(addflag==1){
                OkHttpUtils.postString().url(HttpURL.SAVE_TIMING)
                        .mediaType(MediaType.parse("application/json;charset=UTF-8"))
                        .content(obj.toString())
                        .build().readTimeOut(5000)
                        .writeTimeOut(5000).connTimeOut(5000)
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Request request, Exception e) {
                                showToast("添加定时失败");
                                mSVProgressHUD.dismiss();
                            }

                            @Override
                            public void onResponse(String response) {
                                mSVProgressHUD.dismiss();
                                Log.i("onResponse" , "onResponse:" + response);
                                try {
                                    JSONObject jsonObject = new JSONObject(response);
                                    String value = jsonObject.getString("resultCode");
                                    if (value.equals("1")){
                                        showToast("添加成功");

                                        setResult(ADD_SUCCESS_RESULT_CODE);
                                        finish();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                }else if(addflag==2){
                    //修改定时
                    try {
                        obj.put("id",taskid);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    OkHttpUtils.postString().url(HttpURL.UPDATA_TIMING_TASK)
                            .mediaType(MediaType.parse("application/json;charset=UTF-8"))
                            .content(obj.toString())
                            .build().readTimeOut(5000)
                            .writeTimeOut(5000).connTimeOut(5000)
                            .execute(new StringCallback() {
                                @Override
                                public void onError(Request request, Exception e) {
                                    showToast("修改定时失败");
                                    mSVProgressHUD.dismiss();
                                }

                                @Override
                                public void onResponse(String response) {
                                    mSVProgressHUD.dismiss();
                                    Log.i("onResponse" , "onResponse:" + response);
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String value = jsonObject.getString("resultCode");
                                        if (value.equals("1")){
                                            showToast("修改成功");

                                            setResult(ADD_SUCCESS_RESULT_CODE);
                                            finish();
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                }
                break;
        }
    }
//    06-28 20:29:12.835 4148-4148/com.dotstone.chipism I/sendCmd: cmd:{"a":"20000","b":0,"c":"20,247","d":"10,null","e":1,"f":1530188941841,"h":"0.0.1","g":"{\"cmd\":101,\"data\":[1,155,19,0,2,1,16,255,0,0]}"}
//06-28 20:29:13.355 4148-4148/com.dotstone.chipism I/sendCmd: cmd:{"a":"20000","b":0,"c":"20,247","d":"10,null","e":1,"f":1530188941842,"h":"0.0.1","g":"{\"cmd\":101,\"data\":[1,155,19,0,2,1,16,0,0,0]}"}

    public static int bytesToInt(byte[] src, int offset) {
        int value;
        value = (int) ((src[offset] & 0xFF)
                | ((src[offset+1] & 0xFF)<<8)
                | ((src[offset+2] & 0xFF)<<16)
                | ((src[offset+3] & 0xFF)<<24));
        return value;
    }

    @Override
    public void initParms(Bundle parms) {
        device = DeviceManager.getInstance().getDeviceById(AddSocketTimingManager.getInstance().getId());
        Log.e("","");
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_add_socket_timing1;
    }

    @Override
    public void initView(View view) {
        mStatusBar = $(R.id.tv_statusBar_mian);
        btnBack = $(R.id.back_layout);
        btnAdd = $(R.id.nextstep);
        tvTitle = $(R.id.title_tv);
        npHour = $(R.id.np_timing_h);
        npMIn = $(R.id.np_timing_m);
        time_tv = $(R.id.time_tv);
        save_time_tv = $(R.id.save_time_tv);
        switch_tv = $(R.id.switch_tv);
        repeat_rl = $(R.id.repeat_rl);
        workday_tv = $(R.id.workday_tv);
        deviceid = getIntent().getStringExtra("deviceid");

        sun_selected=ShareParam.getBooleanParam(this,"sun_selected");
        sat_selected=ShareParam.getBooleanParam(this,"sat_selected");
        fri_selected=ShareParam.getBooleanParam(this,"fri_selected");
        thu_selected=ShareParam.getBooleanParam(this,"thu_selected");
        wed_selected=ShareParam.getBooleanParam(this,"wed_selected");
        tue_selected=ShareParam.getBooleanParam(this,"tue_selected");
        mon_selected=ShareParam.getBooleanParam(this,"mon_selected");

      //  cbWeeks.add(sun_selected);
     //   cbWeeks.add(sat_selected);
     //   cbWeeks.add(fri_selected);
     //   cbWeeks.add(thu_selected);
      //  cbWeeks.add(wed_selected);
      //  cbWeeks.add(tue_selected);
      //  cbWeeks.add(mon_selected);

        npHour.setMinValue(0);
        npHour.setMaxValue(23);
        npHour.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        npMIn.setMinValue(0);
        npMIn.setMaxValue(59);

        npMIn.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        npHour .setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
              hour1=newVal;
              if(hour1<10){
                  hour111="0"+hour1;
              }else{
                  hour111=""+hour1;
              }
                if(minute1<10){
                    minute111="0"+minute1;
                }else{
                    minute111=""+minute1;
                }
              time_tv.setText(hour111+":"+minute111);
               String save_time= TimeUtil.getTimeDifference(TimeUtil.getDateToString(System.currentTimeMillis()),hour111+":"+minute111);
               String[] time= save_time.split(";");
                int  h=Integer.parseInt(time[0]);
                int  s=Integer.parseInt(time[1]);
                if(h==0 && s<0){
                    h=23;
                    s=60+s;
                }
                else if(h==0 && s<0){
                    //不处理
                }
                else if(h>0 && s>0){
                    //不处理
                }else if(h>0 && s<0){
                    //不处理
                } else if(h<0 && s<0){
                    h=24+h;
                    s=60+s;
                    if(s>29){
                        h=h-1;
                    }
                }else if(h<0 && s==0){
                    h=24+h;
                }else if(h<0 && s>0){
                    h=24+h;
                    if(s>29){
                        h=h-1;
                    }
                }
                save_time_tv.setText(h+"小时"+s+"分钟后开启");
            }
        });
        npMIn .setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                minute1=newVal;
                if(hour1<10){
                    hour111="0"+hour1;
                }else{
                    hour111=""+hour1;
                }
                if(minute1<10){
                    minute111="0"+minute1;
                }else{
                    minute111=""+minute1;
                }
                time_tv.setText(hour111+":"+minute111);
                String save_time=TimeUtil.getTimeDifference(TimeUtil.getDateToString(System.currentTimeMillis()),hour111+":"+minute111);
                String[] time= save_time.split(";");
                int  h=Integer.parseInt(time[0]);
                int  s=Integer.parseInt(time[1]);
                if(h==0 && s<0){
                    h=23;
                    s=60+s;
                }
                else if(h==0 && s<0){
                    //不处理
                }
                else if(h>0 && s>0){
                    //不处理
                }else if(h>0 && s<0){
                    //不处理
                } else if(h<0 && s<0){
                    h=24+h;
                    s=60+s;
                    if(s>29){
                        h=h-1;
                    }
                }else if(h<0 && s==0){
                    h=24+h;
                }else if(h<0 && s>0){
                    h=24+h;
                    if(s>29){
                        h=h-1;
                    }
                }

                save_time_tv.setText(h+"小时"+s+"分钟后开启");
            }
        });

        mSVProgressHUD = new SVProgressHUD(this);
    }


    /**
     * @param repeat 解析二进制闹钟周期
     * @param flag   flag=0返回带有汉字的周一，周二cycle等，flag=1,返回weeks(1,2,3)
     * @return
     */
    public  String parseRepeat(int repeat, int flag) {
        String cycle = "";
        String weeks = "";
        if (repeat == 0) {
            repeat = 127;
        }
        if (repeat % 2 == 1) {
            cycle = "周一";
            weeks = "1";
        }
        if (repeat % 4 >= 2) {
            if ("".equals(cycle)) {
                cycle = "周二";
                weeks = "2";
            } else {
                cycle = cycle + "," + "周二";
                weeks = weeks + "," + "2";
            }
        }
        if (repeat % 8 >= 4) {
            if ("".equals(cycle)) {
                cycle = "周三";
                weeks = "3";
            } else {
                cycle = cycle + "," + "周三";
                weeks = weeks + "," + "3";
            }
        }
        if (repeat % 16 >= 8) {
            if ("".equals(cycle)) {
                cycle = "周四";
                weeks = "4";
            } else {
                cycle = cycle + "," + "周四";
                weeks = weeks + "," + "4";
            }
        }
        if (repeat % 32 >= 16) {
            if ("".equals(cycle)) {
                cycle = "周五";
                weeks = "5";
            } else {
                cycle = cycle + "," + "周五";
                weeks = weeks + "," + "5";
            }
        }
        if (repeat % 64 >= 32) {
            if ("".equals(cycle)) {
                cycle = "周六";
                weeks = "6";
            } else {
                cycle = cycle + "," + "周六";
                weeks = weeks + "," + "6";
            }
        }
        if (repeat / 64 == 1) {
            if ("".equals(cycle)) {
                cycle = "周日";
                weeks = "7";
            } else {
                cycle = cycle + "," + "周日";
                weeks = weeks + "," + "7";
            }
        }

        return flag == 0 ? cycle : weeks;
    }
    @Override
    public void setListener() {
       addflag=  getIntent().getIntExtra("addflag",1);
      if(addflag==1){
          tvTitle.setText("添加定时");
      }else if(addflag==2){
          tvTitle.setText("修改定时");
      }
        btnAdd.setText("确定");
        btnAdd.setVisibility(View.VISIBLE);
        mStatusBar.setVisibility(View.VISIBLE);
        btnBack.setOnClickListener(this);
        btnAdd.setOnClickListener(this);
        switch_tv.setOnClickListener(this);
        repeat_rl.setOnClickListener(this);

    }

    @Override
    public void doBusiness(Context mContext) {
        TimingData timingData = (TimingData) getIntent().getSerializableExtra("timingData");
        if (timingData != null) {
            //设置为编辑状态
            isUpdate = true;
            String[] pushTimes = timingData.getPushTime().split(":");
            //设置时间
            //获取当前时间
            Calendar calendar = Calendar.getInstance();
            //小时
            hour1 = calendar.get(Calendar.HOUR_OF_DAY);

            npHour.setValue(hour1);
            //分钟
            minute1 = calendar.get(Calendar.MINUTE);

            npMIn.setValue(minute1);
            //time_tv.setText(hour1+":"+minute1);

            if (pushTimes.length > 1) {
               // npHour.setValue(Integer.parseInt(pushTimes[0]));
               // npMIn.setValue(Integer.parseInt(pushTimes[1]));
            }
           time_tv.setText(Integer.parseInt(pushTimes[0])+":"+Integer.parseInt(pushTimes[1]));
            switch_tv.setText(timingData.getTaskName());
          //  workday_tv.setText(timingData.getTaskName());
            if(addflag==1){
                name= ShareParam.getStringParam(this,"name");
                if(!TextUtils.isEmpty(name)){
                    workday_tv.setText(name);
                }
            }else{
                if(timingData.isCycle()==true){
                    workday_tv.setText( parseRepeat(timingData.getPush_week(),0));
                }else{
                    workday_tv.setText("执行一次");
                }

            }
            taskid=timingData.getTaskId();
        }else{
            //获取当前时间
            Calendar calendar = Calendar.getInstance();
            //小时
             hour1 = calendar.get(Calendar.HOUR_OF_DAY);

            npHour.setValue(hour1);
            //分钟
             minute1 = calendar.get(Calendar.MINUTE);

            npMIn.setValue(minute1);
            time_tv.setText(hour1+":"+minute1);
        }
    }


    public static int bitToByte(String bit) {
        int re, len;
        if (null == bit) {
            return 0;
        }
        len = bit.length();
        if (len != 4 && len != 8) {
            return 0;
        }
        if (len == 8) {// 8 bit处理
            if (bit.charAt(0) == '0') {// 正数
                re = Integer.parseInt(bit, 2);
            } else {// 负数
                re = Integer.parseInt(bit, 2) - 256;
            }
        } else {//4 bit处理
            re = Integer.parseInt(bit, 2);
        }
        return (byte) re;
    }


    public static String getBit(byte by){
        StringBuffer sb = new StringBuffer();
        sb.append((by>>7)&0x1)
                .append((by>>6)&0x1)
                .append((by>>5)&0x1)
                .append((by>>4)&0x1)
                .append((by>>3)&0x1)
                .append((by>>2)&0x1)
                .append((by>>1)&0x1)
                .append((by>>0)&0x1);
        return sb.toString();
    }
    public void selectRingWay() {
        SelectRemindWayPopup fp = new SelectRemindWayPopup(this);
        fp.showPopup(tvTitle);
        fp.setOnSelectRemindWayPopupListener(new SelectRemindWayPopup
                .SelectRemindWayPopupOnClickListener() {

            @Override
            public void obtainMessage(int flag) {
                switch (flag) {

                    case 0:
                        workday_tv.setText("执行一次");
                        break;

                    case 1:
                        workday_tv.setText("每天");
                        break;
                    case 2:
                        workday_tv.setText("工作日");
                        break;
                    case 3:
                        workday_tv.setText("周末");
                        break;
                    case 4:
                        workday_tv.setText("自定义。。。");
                        break;
                    default:
                        break;
                }
            }
        });
    }

}
